<template>
  <div class="mysql-migration p-6 space-y-6">
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold mb-4">MySQL 数据迁移工具</h2>
      <button @click="saveSettings" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">
        保存设置
      </button>
    </div>

    <!-- 源数据库配置 -->
    <div class="bg-white shadow rounded-lg p-4">
      <h3 class="font-medium text-lg mb-2">源数据库</h3>
      <div class="grid grid-cols-2 gap-4">
        <input v-model="sourceDb.host" placeholder="服务器地址" class="border px-3 py-2 rounded" />
        <input v-model="sourceDb.port" placeholder="端口号" class="border px-3 py-2 rounded" />
        <input v-model="sourceDb.username" placeholder="用户名" class="border px-3 py-2 rounded" />
        <input v-model="sourceDb.password" type="password" placeholder="密码" class="border px-3 py-2 rounded" />
      </div>
    </div>

    <!-- 目标数据库配置 -->
    <div class="bg-white shadow rounded-lg p-4">
      <h3 class="font-medium text-lg mb-2">目标数据库</h3>
      <div class="flex items-center mb-2">
        <input v-model="targetDb.useDocker" type="checkbox" id="use-docker" class="mr-2" />
        <label for="use-docker">目标 MySQL 运行在 Docker 容器中</label>
      </div>
      <div class="grid grid-cols-2 gap-4">
        <input v-model="targetDb.host" placeholder="服务器地址" class="border px-3 py-2 rounded" />
        <input v-model="targetDb.port" placeholder="端口号" class="border px-3 py-2 rounded" />
        <input v-model="targetDb.username" placeholder="用户名" class="border px-3 py-2 rounded" />
        <input v-model="targetDb.password" type="password" placeholder="密码" class="border px-3 py-2 rounded" />
        <input v-if="targetDb.useDocker" v-model="targetDb.containerName" placeholder="容器名称（可选）"
               class="border px-3 py-2 rounded" />
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="flex space-x-4">
      <button @click="testConnection('source')" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
        测试源数据库连接
      </button>
      <button @click="testConnection('target')" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">
        测试目标数据库连接
      </button>
      <button @click="migrateData" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600">
        开始迁移
      </button>
      <button @click="clearTargetDatabase" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600">
        清空目标数据库
      </button>
    </div>

    <!-- 提示信息 -->
    <div v-if="message" class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4" role="alert">
      <p>{{ message }}</p>
    </div>

    <!-- 日志输出区域 -->
    <div class="bg-gray-100 p-4 rounded h-64 overflow-auto font-mono text-sm" ref="logArea">
      <pre v-html="logOutput"></pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onDeactivated, onActivated } from 'vue'
import { useYklibLoginStore } from 'yklib'

const store = useYklibLoginStore()
const sourceDb = ref({
  host: '',
  port: '3306',
  username: 'root',
  password: ''
})

const targetDb = ref({
  host: '',
  port: '3306',
  username: 'root',
  password: '',
  useDocker: false,         // 新增字段：是否使用 Docker
  containerName: 'mysql_container'        // 新增字段：容器名
})

const message = ref('')
const logOutput = ref('')
const logArea = ref<HTMLElement | null>(null)

function log(text: string) {
  const time = new Date().toLocaleTimeString()
  logOutput.value += `[${time}] ${text}\n`
  // 自动滚动到底部
  if (logArea.value) {
    setTimeout(() => {
      logArea.value!.scrollTop = logArea.value!.scrollHeight
    }, 50)
  }
}

async function testConnection(type: 'source' | 'target') {
  const db = type === 'source' ? sourceDb.value : targetDb.value
  log(`正在测试 ${type === 'source' ? '源' : '目标'} 数据库连接...`)
  try {
    // 调用 pywebview 后端接口
    // @ts-ignore
    const result = await window.pywebview.api.testMySQLConnection(db)
    if (result.suc) {
      log(`✅ ${type === 'source' ? '源' : '目标'}数据库连接成功！`)
      message.value = `${type === 'source' ? '源' : '目标'}数据库连接成功！`
    } else {
      log(`❌ 连接失败：${result.msg}`)
      message.value = `连接失败：${result.msg}`
    }
  } catch (error) {
    log(`❌ 连接异常：${error.message}`)
    message.value = `连接异常：${error.message}`
  }
}

async function migrateData() {
  if (!sourceDb.value.host || !sourceDb.value.port || !sourceDb.value.username ||
    !targetDb.value.host || !targetDb.value.port || !targetDb.value.username) {
    message.value = '请填写完整的数据库连接信息！'
    return
  }

  log('开始迁移数据...')
  try {
    // 调用 pywebview 后端接口执行迁移
    // @ts-ignore
    const result = await window.pywebview.api.migrateMySQL(sourceDb.value, targetDb.value)

    if (result.suc) {
      log('✅ 数据迁移完成！')
      message.value = '数据迁移完成！'
    } else {
      log(`❌ 数据迁移失败：${result.msg}`)
      message.value = `数据迁移失败：${result.msg}`
    }
  } catch (error) {
    log(`❌ 数据迁移错误：${error.message}`)
    message.value = `数据迁移错误：${error.message}`
  }
}

async function clearTargetDatabase() {
  if (!targetDb.value.host || !targetDb.value.port || !targetDb.value.username) {
    message.value = '请先填写目标数据库连接信息！'
    return
  }

  if (!confirm('此操作将删除目标数据库中的所有非系统数据库和用户，是否继续？')) return

  log('正在清空目标数据库...')
  try {
    // 调用 pywebview 后端接口执行清空
    // @ts-ignore
    const result = await window.pywebview.api.clearMySQLDatabase(targetDb.value)

    if (result.suc) {
      log('✅ 目标数据库已清空！')
      message.value = '目标数据库已清空！'
    } else {
      log(`❌ 清空失败：${result.msg}`)
      message.value = `清空失败：${result.msg}`
    }
  } catch (error) {
    log(`❌ 清空错误：${error.message}`)
    message.value = `清空错误：${error.message}`
  }
}

// 组件加载时读取配置
onMounted(async () => {
  const savedConfig = await store.loadProjectSettings('moveMySQL')
  if (savedConfig) {
    sourceDb.value = savedConfig.sourceDb || sourceDb.value
    targetDb.value = savedConfig.targetDb || targetDb.value
  }
})

function saveSettings() {
  store.saveProjectSettings({
    'moveMySQL': {
      sourceDb: sourceDb.value,
      targetDb: targetDb.value
    }
  })
  log('✅ 数据库配置已保存')
  message.value = '数据库配置已保存'
}
</script>
